import { Component, OnInit, ViewEncapsulation, ChangeDetectionStrategy, Input } from '@angular/core';

import {Subscription} from "rxjs/Subscription";
import {Subject} from "rxjs/Rx";
import { Router} from "@angular/router";
import {ToolsService} from "@shared/service/tools/tools.service";
import {AuthService} from "@shared/service/auth/auth.service";
import {CommunityService} from "../../community.service";
import {SocialCircle} from "@interface/index";



@Component({
  selector: 'circle-item',
  templateUrl: './circle-item.component.html',
  styleUrls: ['./circle-item.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class CircleItemComponent implements OnInit {
  public ngUnsubscribe: Subject<void> = new Subject<void>();
  public subscription: Subscription = new Subscription();
  public _circleList: Array<SocialCircle>;
  public hasLogin = false;
  public  userId;
  @Input() showButton: boolean;
  @Input()
  set circleList(val: Array<SocialCircle>) {
    this._circleList = val;
  }

  get circleList(): Array<SocialCircle> {
    return this._circleList;
  }


  constructor(
    public router: Router,
    public communityService: CommunityService,
    public toolsService: ToolsService,
    private auth: AuthService
  ) {
    this.userId = this.auth.getUserId();
  }
  // 跳转圈子详情
  goToCirclesDetail(circle: SocialCircle) {
    this.router.navigate([`/community/circle`, circle.circleId]);
  }

  /**
   * @description 点击第一次加入圈子，再次点击则该退出圈子；
   * @author zhupw1360
   * @params id，i（下标）
   * @date 2017-12-13
   */
  postJoinCircle(id: number, i: number) {
    if (this.auth.hasLoggedIn() ) {
      this.hasLogin = true;
      if (this.circleList[i].myJoin === false) {
        this.communityService.postJoinCircle({id: id})
          .takeUntil(this.ngUnsubscribe).subscribe(res => {
          if (res.result === '0' ) {
            this.toolsService.showToast('加入成功');
            this.circleList[i].myJoin = true; // 是否加入过此圈子
          }
        });
      }else {
        this.communityService.quitCircle(id)
          .takeUntil(this.ngUnsubscribe).subscribe(res => {
          if (res.result === '0' ) {
            this.toolsService.showToast('退出成功');
            this.circleList[i].myJoin = false; // 是否加入过此圈子
          }
        });
      }
    } else {
      this.toolsService.presentConfirm('此操作需要登录,是否前往登录', 1, this.goToLogin.bind(this));
      return;
    }
  }


  // 跳转登录页面
  goToLogin() {
    this.router.navigate(['/auth/login']);
  }


  ngOnInit() {

  }

}
